


ALTER FUNCTION func_Find_MaDLGoc
(
	@MaDLGoc varchar(6)
	, @Ngay date
)
RETURNS varchar(6)
WITH encryption
AS
BEGIN
	Declare @GocMoi varchar(6) = @MaDLGoc
	
	WHILE @GocMoi is not null
		BEGIN
			SET @GocMoi =	(
								SELECT TOP 1 Ma_DaiLyCu
								FROM KQXS.dbo.tblChuyenDL
								WHERE Ma_DaiLyMoi = @MaDLGoc
									and Ngay < @Ngay
								ORDER BY Ngay DESC
							)
			IF @GocMoi is not null 
				BEGIN
					SET @Ngay =(
									SELECT TOP 1 Ngay
									FROM KQXS.dbo.tblChuyenDL
									WHERE Ma_DaiLyMoi = @MaDLGoc
										and Ngay < @Ngay
									ORDER BY Ngay DESC
								)
					SET @MaDLGoc = @GocMoi
				END
		END
		
	RETURN @MaDLGoc	
END